﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CommerceOne.Common;
using CommerceOne.Controllers;
using CommerceOne.Domains.IRepositories;
using CommerceOne.Domains.SqlRepositories;


namespace CommerceOne.Widgets.NewestProducts
{
    public class NewestProductController : ControllerBase
    {
        private readonly IProductRepository _context = SqlProductRepository.Instance;

        /// <summary>
        /// Gets the view model.
        /// </summary>
        /// <returns></returns>
        public NewestProductViewModel GetViewModel()
        {
            string configPath = @"Configurations\NewestProduct.xml";
            configPath = this.HttpContextBase.Server.MapPath(configPath);

            var configuration = SerializeService.Instance.DeserializeObject<Configurations>(configPath);

            var viewModel = new NewestProductViewModel();
            if (configuration == null) throw new Exception("Config file doesnot existed. Check file: " + configPath);

            viewModel.Products = _context.GetTopNewestProduct(configuration.NumberOfProduct);
            foreach (var item in viewModel.Products)
            {
                item.Url = UrlBuilderService.Instance.GetUrlRoute(PageType.ProductDetail, item.ID, 1, item.Name, string.Empty);
                if (item.ProductPhoto != null)
                {
                    foreach (var photoItem in item.ProductPhoto)
                    {
                        if (!string.IsNullOrEmpty(photoItem.Home)) photoItem.Home = DisplayUtil.GetImageUrl(photoItem.Home);
                        if (!string.IsNullOrEmpty(photoItem.Large)) photoItem.Large = DisplayUtil.GetImageUrl(photoItem.Large);
                        if (!string.IsNullOrEmpty(photoItem.Medium)) photoItem.Medium = DisplayUtil.GetImageUrl(photoItem.Medium);
                        if (!string.IsNullOrEmpty(photoItem.ThickBox)) photoItem.ThickBox = DisplayUtil.GetImageUrl(photoItem.ThickBox);
                    }
                }

                item.ShortName = item.Name;
                if (item.ShortName.Length <= configuration.MaximumProductName) continue;
                item.ShortName = item.Name.Substring(0, configuration.MaximumProductName) + "...";
            }
            return viewModel;
        }

        #region Singleton Instance
        private static NewestProductController _instance;

        public static NewestProductController Instance
        {
            get
            {
                if (_instance == null) _instance = new NewestProductController();
                return _instance;
            }
        }

        #endregion
    }
}